<?php
namespace app\mogo\model;

use think\Model;
use traits\model\SoftDelete;
use think\Validate;
class Message extends Model
{
    use SoftDelete;
    protected $table = 'dp_mogo_message';
    protected $autoWriteTimestamp = true;
    protected $type = [
        'extra'=>'json'
    ];

    // 关联被通知人
    public function user(){
        return $this->belongsTo(config('user_model'))->field([
            config('user_filed.nickname'),
            config('user_filed.avatar'),
            config('user_table').'.id'
        ]);
    }
    // 关联回复人
    public function at(){
        return $this->belongsTo(config('user_model'),'at_id')->field([
            config('user_filed.nickname'),
            config('user_filed.avatar'),
            config('user_table').'.id'
        ]);
    }

    // 将消息设置为已读
    static public function read($id){
        $msg = self::get($id);
        if(!$msg)  exception('该消息不存在');
        $msg->is_read = 1;
        return $msg->save();
    }

    static public function push_message($data){
        $validate = new Validate([
            'user_id'  => 'require',
            'content' => 'require',
            'at_id' => 'require',
        ]);
        if (!$validate->check($data)) {
            exception($validate->getError());
        }

//        halt(self::create($data));
        return self::create($data);
    }
    
}
